package service;

import mapper.MemoryMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import po.ComboboxItem;
import po.Memory;
import po.Result;

import java.util.ArrayList;
import java.util.List;

@Service
public class MemoryServiceImpl implements MemoryService {
    @Autowired
    private MemoryMapper memoryMapper;

    @Override
    public List<Memory> findAllMemories(Memory memory) throws Exception {
        return memoryMapper.findAllMemories(memory);
    }

    @Override
    public Result addMemory(Memory memory) {
        Result result = new Result();
        try {
            memoryMapper.addMemory(memory);
        } catch (Exception e) {
            result.setResult("fail");
            result.setMessage("添加失败！");
            return result;
        }
        result.setResult("success");
        result.setMessage("添加成功！");
        return result;
    }

    @Override
    public Result deleteMemoryById(int id) {
        Result result = new Result();
        try {
            memoryMapper.deleteMemoryById(id);
        } catch (Exception e) {
            result.setResult("fail");
            result.setMessage("删除失败！");
            return result;
        }
        result.setResult("success");
        result.setMessage("删除成功！");
        return result;
    }

    @Override
    public List<ComboboxItem> findMemoryForComb() throws Exception {
        List<Memory> memoryList = memoryMapper.findAllMemories(null);
        List<ComboboxItem> list = new ArrayList<>();
        for (Memory memory : memoryList) {
            ComboboxItem item = new ComboboxItem();
            item.setId(memory.getId());
            item.setText(memory.toString());
            list.add(item);
        }
        return list;
    }

    @Override
    public Result updateMemoryById(int id, Memory memory) {
        Result result = new Result();
        try {
            memory.setId(id);
            memoryMapper.updateMemoryById(memory);
        } catch (Exception e) {
            result.setResult("fail");
            result.setMessage("修改失败！");
            return result;
        }
        result.setResult("success");
        result.setMessage("修改成功！");
        return result;
    }
}
